package com.guandi.geekbrowser.primary.repository;

import com.guandi.geekbrowser.primary.entity.Details;
import com.guandi.geekbrowser.primary.entity.Ipool;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import javax.transaction.Transactional;
import java.util.List;

@Repository
public interface IpoolRepository extends JpaRepository<Ipool,Long>, JpaSpecificationExecutor<Ipool> {

    List<Ipool> findByUserIdAndUsestatus(String id, Integer use);

    List<Ipool> findByUserIdAndUsestatusAndCountry(String id, Integer use,String country);

    List<Ipool> findByUserIdAndUsestatusAndType(String id, Integer use,Integer type);

    List<Ipool> findByUserIdAndType(String id,Integer type);

    List<Ipool> findByUserIdAndUsestatusAndTypeOrderByPortAsc(String id, Integer use,Integer type);

    List<Ipool> findByUserIdAndUsestatusAndTypeAndCountryOrderByPortAsc(String id, Integer use,Integer type,String country);

    List<Ipool> findByUserIdAndUsestatusAndTypeAndCountryAndBindOrderByPortAsc(String id, Integer use,Integer bind,Integer type,String country);

    Ipool findByUserIdAndAddressAndPort(String id, String address, String port);

    Ipool findByUserIdAndId(String userId, Long id);

    Ipool findByAddressAndPort(String address, String port);

    List<Ipool> findByCountryAndType(String country, Integer type);

    Ipool findByAddressAndPortAndUserId(String address, String port,String userId);

    Ipool findByAddressAndPortAndUserIdAndCountry(String address, String port,String userId,String country);

    @Query(value = "UPDATE Ipool d SET d.type = ?2 where d.id = ?1")
    @Modifying
    @Transactional
    Integer updateType(Long id, Integer type);

    @Query(value = "UPDATE Ipool d SET d.usestatus = ?2 where d.id = ?1")
    @Modifying
    @Transactional
    Integer updateUsestatus(Long id, Integer usestatus);

    @Transactional
    void deleteByIdAndUserId(Long id, String userId);

    Page<Ipool> findAll(Specification<Ipool> specification, Pageable pageable);

    List<Ipool> findAll(Specification<Ipool> specification);

    @Query(nativeQuery = true,value = "select * from ipool where user_id=?1 and type = ?2 order by rand() limit 1")
    Ipool findByUserIdAndTypeQuery(String userId,Integer type);
}
